#include "StdAfx.h"
#include "cEffectSprite.h"
#include "cQuadVertexObj.h"

cEffectSprite::cEffectSprite(void)
{
	mpTexture		 = NULL;
	uiCurrentCnt	 = 0;
}

cEffectSprite::~cEffectSprite(void)
{
}

void cEffectSprite::Init( const char* szFileName, UINT ColNum, UINT RowNum, UINT DumyNum, D3DCOLOR color )
{
	assert( NULL != szFileName && (ColNum !=0 || RowNum !=0 ) );

	D3DXIMAGE_INFO info;

	HR(::D3DXCreateTextureFromFileEx( gd3dDevice,
		szFileName,
		D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2,
		D3DX_DEFAULT,
		0,
		D3DFMT_UNKNOWN,
		D3DPOOL_MANAGED,
		D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR,
		D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR,
		color,
		&info,
		NULL, 
		&mpTexture ));

	FLOAT fColLength = info.Width/( FLOAT )ColNum;
	FLOAT fRowLength = info.Height/( FLOAT )RowNum;

	FLOAT fTexCoordWidth = fColLength / ( FLOAT )info.Width;
	FLOAT fTexCoordHeight = fRowLength / ( FLOAT )info.Height;

	for ( UINT y  = 0; y<RowNum; y++ )
	{
		for ( UINT x = 0; x<ColNum; x++ )
		{
			cQuadVertexObj* pQuadVertex = new cQuadVertexObj;
			pQuadVertex->Init( mpTexture, x * fTexCoordWidth, y * fTexCoordHeight, fTexCoordWidth, fTexCoordHeight );

			mFrames.push_back( pQuadVertex );
		}
	}

	if ( DumyNum)
	{
		UINT MaxSize = mFrames.size();
		for ( UINT i = MaxSize - 1; i >= MaxSize - DumyNum; i-- )
		{
			mFrames[i]->Release();
			delete mFrames[i];

			mFrames.pop_back();
		}
	}
}

void cEffectSprite::release()
{
	for ( UINT i = 0; i< mFrames.size(); ++i )
	{
		mFrames[i]->Release();
		delete mFrames[i];
	}
	mFrames.clear();

	if ( mpTexture )
	{
		ULONG cnt = mpTexture->Release();
		if ( cnt == 0 ) mpTexture = NULL;
	}
}

void cEffectSprite::Render( FLOAT x, FLOAT y, FLOAT z, float scale )
{
	PreRender();
	
	mFrames[uiCurrentCnt]->SetScale( scale );
	mFrames[uiCurrentCnt]->Draw( x, y, z );

	PostRender();
}

void cEffectSprite::PreRender()
{
	gd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ) ;
	gd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR ) ;
	gd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE ) ;
}

void cEffectSprite::PostRender()
{
	gd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ) ;
	gd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ) ;
	gd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ) ;
}